package gui.productgroup;

import core.ContainerFacade;
import core.exception.ModelException;
import gui.common.*;
import gui.inventory.*;

/**
 * Controller class for the add product group view.
 */
public class AddProductGroupController extends Controller implements
		IAddProductGroupController {
	
	private ProductContainerData _parent;
	
	/**
	 * Constructor.
	 * 
	 * @param view Reference to add product group view
	 * @param container Product container to which the new product group is being added
	 */
	public AddProductGroupController(IView view, ProductContainerData container) {
		super(view);
		
		_parent = container;
		getView().setSupplyValue("0");
		
		construct();
	}

	//
	// Controller overrides
	//
	
	/**
	 * Returns a reference to the view for this controller.
	 * 
	 * {@pre None}
	 * 
	 * {@post Returns a reference to the view for this controller.}
	 */
	@Override
	protected IAddProductGroupView getView() {
		return (IAddProductGroupView)super.getView();
	}

	/**
	 * Sets the enable/disable state of all components in the controller's view.
	 * A component should be enabled only if the user is currently
	 * allowed to interact with that component.
	 * 
	 * {@pre None}
	 * 
	 * {@post The enable/disable state of all components in the controller's view
	 * have been set appropriately.}
	 */
	@Override
	protected void enableComponents() {
		// There are 4 components that can be enabled/disabled.
		// The only one we care about is the okay button.
		getView().enableOK(ContainerFacade.instance().canAddProductGroup(
				_parent.getContainer(),
				getView().getProductGroupName()) &&
				ContainerFacade.instance().validThreeMonthSupply(
						getView().getSupplyValue(), 
						getView().getSupplyUnit().toString())
				);
	}

	/**
	 * Loads data into the controller's view.
	 * 
	 *  {@pre None}
	 *  
	 *  {@post The controller has loaded data into its view}
	 */
	@Override
	protected void loadValues() {
	}

	//
	// IAddProductGroupController overrides
	//

	/**
	 * This method is called when any of the fields in the
	 * add product group view is changed by the user.
	 */
	@Override
	public void valuesChanged() {
		enableComponents();
	}
	
	/**
	 * This method is called when the user clicks the "OK"
	 * button in the add product group view.
	 */
	@Override
	public void addProductGroup() {
		try {
			ContainerFacade.instance().addProductGroup(
					_parent.getContainer(), 
					getView().getProductGroupName(), 
					getView().getSupplyValue(), 
					getView().getSupplyUnit().toString());
		} catch (ModelException e) {
			getView().displayErrorMessage("There was a problem adding the product group: " 
					+ e.getMessage());

		}
	}
}

